'use strict';

module.exports = (option, app) => {
  return async (ctx, next) => {
    try {
      await next();
    } catch (e) {
      let status = e.status || 500;
      if (status === 500) app.emit('error', e, ctx);
      let error;
      if (status === 500 && app.config.env === 'prod') {
        error = 'server_error';
      } else if (status === 422) {
        status = 400;
        error = 'invalid_request';
      } else {
        error = e.message;
      }
      ctx.body = { error };
      ctx.body.detail = e.errors;
      ctx.status = status;
    }
  };
};
